﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Ue.Extensions
{
    public static class ObjectExtensions
    {
        #region GetCombineHashCode

        public static int GetCombineHashCode(this object col,params object[] args)
        {
            int? h1 = col == null
                ? new Nullable<int>()
                : col.GetHashCode();

            if (args != null)
            {
                foreach (var item in args)
                {
                    if (item != null)
                    {
                        h1 = h1 == null
                            ? item.GetHashCode()
                            : GetCombineHashCode(h1.Value, item.GetHashCode());
                    }
                }
            }

            return h1 == null
                ? 0
                : h1.Value;
        }
        public static int GetCombineHashCode(int h1, int h2)
        {
            return ((h1 << 5) + h1) ^ h2;
        }

        #endregion

        #region Format

        /// <summary>
        /// 将对象格式化为指定格式的字符串
        /// 如：日期格式 yyyy-MM-dd
        /// </summary>
        /// <param name="col">要格式化的对象</param>
        /// <param name="format">要使用的格式</param>
        /// <returns></returns>
        public static string Format(this object col, string format)
        {
            if (null == col)
            {
                return string.Empty;
            }
            IFormattable formattable = col as IFormattable;
            if (null != formattable)
            {
                return formattable.ToString(format, null);
            }

            var colType = col.GetType();
            if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                object underlyingValue = Convert.ChangeType(col, Nullable.GetUnderlyingType(col.GetType()));
                return Format(underlyingValue, format);
            }

            return col.ToString();
        }

        #endregion

        #region Serializer

        public static string XmlSerializer<T>(this T col)
        {
            string xmlString = string.Empty;

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, col);

                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        #endregion
    }
}
